package com.ruoyi.web.controller.api;

import com.github.pagehelper.PageInfo;
import com.ruoyi.common.utils.ApiResult;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.mall.domain.*;
import com.ruoyi.mall.domain.vo.MallCartGoodsVO;
import com.ruoyi.mall.domain.vo.MallOrderGoodsVO;
import com.ruoyi.mall.service.*;
import com.ruoyi.web.controller.utils.XiaochengxuPayService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @ClassName ApiOrderController
 * @Description 请描述类的业务用途
 * @Author linlinee
 * @Date 2021/11/30 10:03 AM
 * @Version 1.0
 **/

@RestController
@RequestMapping("/api/order")
@ResponseBody
public class ApiOrderController {

    @Autowired
    IMallOrderOrderService orderService;

    @Autowired
    IMallGoodsGoodsService goodsService;

    @Autowired
    IMallGoodsProductService productService;

    @Autowired
    IMallGoodsSpecValueService specValueService;

    @Autowired
    IMallMemberAddressService addressService;

    @Autowired
    IMallMemberUserService memberUserService;

    @Autowired
    XiaochengxuPayService xiaochengxuPayService;

    @Autowired
    IMallOrderCommentService orderCommentService;

    @Autowired
    IMallOrderBackService orderBackService;

    @Autowired
    IMallOrderGoodsService orderGoodsService;

    @Autowired
    IMallMemberCartService memberCartService;

    @Autowired
    IMallTargetService mallTargetService;

    @PostMapping("/creatOrderByGoods")
    public ApiResult creatOrderByGoods(@RequestBody Map<String, Object> params){
        if (!params.containsKey("userId")||StringUtils.isEmpty(params.get("userId").toString())){
            return ApiResult.error("用户Id为空");
        }
        if (!params.containsKey("goodId")||StringUtils.isEmpty(params.get("goodId").toString())){
            return ApiResult.error("商品id为空");
        }
        if (!params.containsKey("productId")||StringUtils.isEmpty(params.get("productId").toString())){
            return ApiResult.error("规格id为空");
        }
        if (!params.containsKey("addressId")||StringUtils.isEmpty(params.get("addressId").toString())){
            return ApiResult.error("收货地址id为空");
        }
        if (!params.containsKey("count")||Integer.parseInt(params.get("count").toString())<=0){
            return ApiResult.error("商品数量不能为0");
        }
        if (!params.containsKey("buyerMsg")){
            return ApiResult.error("缺少参数");
        }

        if (params.containsKey("couponId")){
            String couponId = params.get("couponId").toString();
            //查看优惠券是否可用
            if (!StringUtils.isEmpty(couponId)){
                Map<String, Object> map = memberUserService.checkCouponUsed(couponId,Long.valueOf(params.get("userId").toString()));
                if (map==null){
                    return ApiResult.error("优惠券异常");
                }
            }
        }

        try {
            MallOrderOrder order = orderService.creatOrderByGoods(params);
            if (order == null){
                return ApiResult.error("库存不足");
            }else {
                Map<String, Object> map = new HashMap<>();
                map.put("orderId",order.getId());
                map.put("price",order.getPayment());
                map.put("orderNo",order.getOrderNo());
                return ApiResult.ok().put("data",map);
            }
        }catch (Exception e){
            return ApiResult.error("下单失败");
        }
    }

    @PostMapping("/creatOrderByShopCarts")
    public ApiResult creatOrderByShopCarts(@RequestBody Map<String, Object> params){
        if (!params.containsKey("userId")){
            return ApiResult.error("用户Id为空");
        }
        if (!params.containsKey("cartIds")){
            return ApiResult.error("购物车Id为空");
        }
        if (!params.containsKey("addressId")){
            return ApiResult.error("收货地址id为空");
        }
        if (!params.containsKey("buyerMsg")){
            return ApiResult.error("缺少参数");
        }

        if (params.containsKey("couponId")){
            String couponId = params.get("couponId").toString();
            //查看优惠券是否可用
            if (!StringUtils.isEmpty(couponId)){
                Map<String, Object> map = memberUserService.checkCouponUsed(couponId,Long.valueOf(params.get("userId").toString()));
                if (map==null){
                    return ApiResult.error("优惠券异常");
                }
            }
        }

        try {
            MallOrderOrder order = orderService.creatOrderByCartIds(params);
            if (order == null){
                return ApiResult.error("库存不足");
            }else {
                Map<String, Object> map = new HashMap<>();
                map.put("orderId",order.getId());
                map.put("price",order.getPayment());
                map.put("orderNo",order.getOrderNo());
                return ApiResult.ok().put("data",map);
            }
        }catch (Exception e){
            return ApiResult.error("下单失败");
        }
    }

    /**
     * 微信小程序支付接口
     * @param params
     * @param req
     * @return
     */
    @RequestMapping("/xiaochengxuPay")
    @ResponseBody
    public ApiResult xiaochengxuPay(@RequestBody Map<String, Object> params, HttpServletRequest req) {
        try {
            if (!params.containsKey("orderId") ||!params.containsKey("userId")) {
                return ApiResult.error(100, "缺少参数");
            }
            String orderId = params.get("orderId").toString();
            String userId = params.get("userId").toString();
//            String openid = params.get("openid").toString();
            MallMemberUser userDO = memberUserService.selectMallMemberUserById(Long.parseLong(userId));
            if (userDO == null) {
                return ApiResult.error(103, "用户异常");
            }
            MallOrderOrder orderSubject = orderService.selectMallOrderOrderById(Long.parseLong(orderId));
            if (orderSubject == null) {
                return ApiResult.error(101, "订单异常");
            }
            SortedMap<String, String> signMap = new TreeMap<>();

            signMap.put("body", "五寸方商品"); //商品描述  必
            signMap.put("attach", "五寸方商品"); //商品描述  必
//			signMap.put("body", expertDO.getName()); //商品描述  必
            signMap.put("openid", userDO.getOpenid()); //商品详情  非
//			signMap.put("attach", expertDO.getName()); //商品详情  非
            signMap.put("out_trade_no", orderSubject.getOrderNo()); //商户订单号  必
            float sessionmoney = Float.parseFloat(orderSubject.getPayment().toString());
            String finalmoney = String.format("%.2f", sessionmoney);
            finalmoney = finalmoney.replace(".", "");
            String newStr = finalmoney.replaceFirst("^0*", "");
            signMap.put("total_fee", newStr); //总金额  必
            signMap.put("spbill_create_ip", StringUtils.getRemoteAddr(req)); //终端ip  用户端ip  必

            Map<String,Object> relMap = xiaochengxuPayService.getOrderSignature(signMap);
            return ApiResult.ok().put("data", relMap);

        } catch (Exception e) {
            return ApiResult.error("返回调起微信支付参数失败!");
        }
    }

    /*
     * 取消订单
     * */
    @PostMapping("/cancleOrder")
    public ApiResult cancleOrder (@RequestBody Map<String, Object> params){

        try {
            if (!params.containsKey("orderId")||StringUtils.isEmpty(params.get("orderId").toString())){
                return ApiResult.error("缺少参数");
            }
            MallOrderOrder order = orderService.selectMallOrderOrderById(Long.parseLong(params.get("orderId").toString()));
            Boolean isAccept = orderService.orderStatusRoute(Integer.parseInt("8"),params.get("orderId").toString());
            if (isAccept == true) {
                order.setStatus("8");
                SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                order.setCompleteAt(formatter.format(new Date()));
                return orderService.updateMallOrderOrderByCancle(order);

            }else {
                return ApiResult.error("订单异常");
            }

        } catch (Exception e) {
            return ApiResult.ok("取消订单失败");
        }
    }

    /*
    * 确认收货
    * */
    @PostMapping("/orderReceived")
    public ApiResult orderReceived (@RequestBody Map<String, Object> params){

        try {
            if (!params.containsKey("orderId")||StringUtils.isEmpty(params.get("orderId").toString())){
                return ApiResult.error("缺少参数");
            }
            MallOrderOrder order = orderService.selectMallOrderOrderById(Long.parseLong(params.get("orderId").toString()));
            SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            order.setCompleteAt(formatter.format(new Date()));
            order.setEnterAt(formatter.format(new Date()));
            Boolean isAccept = orderService.orderStatusRoute(Integer.parseInt("3"),params.get("orderId").toString());
            if (isAccept == true) {
                order.setStatus("3");
                int status = orderService.updateMallOrderOrder(order);
                return status > 0 ? ApiResult.ok("确认收货成功") : ApiResult.ok("确认收货失败");
            }else {
                return ApiResult.error("订单异常");
            }
        } catch (Exception e) {
            return ApiResult.ok("确认收货失败");
        }
    }

    /*
    * 订单评价
    * */
    @PostMapping("/orderComment")
    public ApiResult orderComment (@RequestBody Map<String, Object> params){
        if (!params.containsKey("orderId")||StringUtils.isEmpty(params.get("orderId").toString())
                || !params.containsKey("userId")||StringUtils.isEmpty(params.get("userId").toString())
                || !params.containsKey("commentList")||StringUtils.isEmpty(params.get("commentList").toString())){
            return ApiResult.error("缺少参数");
        }
        Boolean isAccept = orderService.orderStatusRoute(Integer.parseInt("4"),params.get("orderId").toString());
        if (isAccept == true) {
            int status = orderCommentService.commentOrder(params);
            return status > 0 ? ApiResult.ok("评价成功") : ApiResult.ok("评价失败");
        }else {
            return ApiResult.error("订单异常");
        }
    }

    /*
     * 申请退款
     * */
    @PostMapping("/applyForRefund")
    public ApiResult applyForRefund (@RequestBody Map<String, Object> params){
        if (!params.containsKey("userId")||StringUtils.isEmpty(params.get("userId").toString())
                || !params.containsKey("orderId")||StringUtils.isEmpty(params.get("orderId").toString())){
            return ApiResult.error("缺少参数");
        }
        Boolean isAccept = orderService.orderStatusRoute(Integer.parseInt("5"),params.get("orderId").toString());
        if (isAccept == true) {
            int status = orderBackService.applyForRefund(params);
            return status > 0 ? ApiResult.ok("申请退款中") : ApiResult.error("不能申请退款");
        }else {
            return ApiResult.error("订单异常");
        }

    }

    /*
     * 取消退款
     * */
    @PostMapping("/cancleRefund")
    public ApiResult cancleRefund (@RequestBody Map<String, Object> params){
        if (!params.containsKey("refundId")||StringUtils.isEmpty(params.get("refundId").toString())){
            return ApiResult.error("缺少参数");
        }
        Boolean isAccept = orderService.refundStatusRoute(Integer.parseInt("2"),params.get("refundId").toString());
        if (isAccept == true) {
            int status = orderBackService.cancleRefund(params);
            return status > 0 ? ApiResult.ok("取消成功") : ApiResult.ok("取消失败");
        }else {
            return ApiResult.error("订单异常");
        }
    }

    /*
     * 获取订单列表
     * */
    @GetMapping("/getOrdersByType")
    public ApiResult getOrdersByType (@RequestParam Map<String, Object> params){
        if (!params.containsKey("type")
                ||!params.containsKey("pageNum")
                ||!params.containsKey("pageSize")
                ||!params.containsKey("userId")
                ){
            return ApiResult.error("参数异常");
        }

        PageInfo<MallOrderOrder> pageInfo = orderService.selectOrdersByType(params.get("pageNum").toString(),params.get("pageSize").toString(),params.get("type").toString(),params.get("userId").toString());
        return ApiResult.ok("取消成功").put("data", pageInfo);
    }

    /*
     * 根据id获取订单
     * */
    @GetMapping("/getOrderByID")
    public ApiResult getOrderByID (@RequestParam Map<String, Object> params){
        if (!params.containsKey("orderId")){
            return ApiResult.error("参数异常");
        }

        try {
            MallOrderOrder order = orderService.selectMallOrderOrderById(Long.parseLong(params.get("orderId").toString()));
            List<MallOrderGoodsVO> orderGoodsVOList = orderGoodsService.selectMallOrderGoodsByOrderId(order.getId());
            order.setGoodsVOList(orderGoodsVOList);
            if ("5".equals(order.getStatus()) || "6".equals(order.getStatus())){
                List<MallOrderBack> list = orderBackService.selectMallOrderBackByOrderId(Long.parseLong(params.get("orderId").toString()));
                MallOrderBack result = new MallOrderBack();
                for (MallOrderBack orderBack: list) {
                    result = orderBack;
                }
                order.setOrderBack(result);
            }
            return ApiResult.ok().put("data", order);
        }catch (Exception e) {
            return ApiResult.ok("获取订单失败");
        }
    }

    //付款之后修改收货地址
    @PostMapping("/changeOrderAddress")
    public ApiResult changeOrderAddress (@RequestBody Map<String, Object> params){
        if (!params.containsKey("orderId") || !params.containsKey("addressId")){
            return ApiResult.error("参数异常");
        }

        try {
            MallOrderOrder order = orderService.selectMallOrderOrderById(Long.parseLong(params.get("orderId").toString()));
            MallMemberAddress address = addressService.selectMallMemberAddressById(Long.parseLong(params.get("addressId").toString()));
            if ("2".equals(order.getStatus()) || "1".equals(order.getStatus())){
                if ("1".equals(order.getIsChangeAddress())){
                    return ApiResult.error("收货地址只能修改一次");
                }
                if (address == null){
                    return ApiResult.error("收货地址不存在");
                }
                order.setIsChangeAddress("1");
                order.setReceiverPhone(address.getPhone());
                order.setReceiverAddress(address.getAddress());
                order.setReceiverArea(address.getArea());
                order.setReceiverCity(address.getCity());
                order.setReceiverProvince(address.getProvince());
                order.setReceiverName(address.getName());
                orderService.updateMallOrderOrder(order);
                return ApiResult.ok().put("data", order);
            }else {
                return ApiResult.error("当前订单状态无法修改");
            }

        }catch (Exception e) {
            return ApiResult.ok("修改收货地址失败");
        }
    }


    /*
    * 所有订单的金额
    * */
    @GetMapping("/checkTotlePriceAndTotleCount")
    public ApiResult checkTotlePriceAndTotleCount(@RequestParam Map<String, Object> params){
        Map<String,Object>map = new HashMap<>();

        int count = orderService.checkTotleCount();
        BigDecimal price = orderService.checkTotlePrice();
        map.put("totleCount",count);
        map.put("totlePrice",price);
        return ApiResult.ok().put("data",map);
    }

    /*
     * 按月、按年查询
     * */
    @GetMapping("/checkTotlePriceByTime")
    public ApiResult checkTotlePriceByTime(@RequestParam Map<String, Object> params){
        if (!params.containsKey("year")){
            return ApiResult.error("参数异常");
        }
        MallTarget target = new MallTarget();

        List<MallTarget> list = mallTargetService.selectMallTargetList(new MallTarget());
        if (list.size() > 0){
            target = list.get(0);
        }
        Map<String,Object>map = new HashMap<>();
        map.put("target",target);

        BigDecimal price = orderService.checkYearAndMonth(params.get("year").toString(),null,null);
        map.put("yearPrice",price);
        int count = orderService.checkCountYearAndMonth(params.get("year").toString(),null,null);
        map.put("yearCount",count);


        if (params.containsKey("month") && params.get("month").toString().length() > 0){
            BigDecimal monthPrice = orderService.checkYearAndMonth(params.get("year").toString(),params.get("month").toString(),null);
            map.put("monthPrice",monthPrice);

            int monthCount = orderService.checkCountYearAndMonth(params.get("year").toString(),params.get("month").toString(),null);
            map.put("monthCount",monthCount);
        }

        if (params.containsKey("month") && params.get("month").toString().length() > 0
                && params.containsKey("day") && params.get("day").toString().length() > 0){
            BigDecimal dayPrice = orderService.checkYearAndMonth(params.get("year").toString(),params.get("month").toString(),params.get("day").toString());
            map.put("dayPrice",dayPrice);

            int dayCount = orderService.checkCountYearAndMonth(params.get("year").toString(),params.get("month").toString(),params.get("day").toString());
            map.put("dayCount",dayCount);
        }

        return ApiResult.ok().put("data",map);
    }
}
